package com.grandbroad.eim.ui.activities;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.easy.west.westclient.Constants;
import com.easy.west.westclient.api.login.bean.ReturenUser;
import com.easy.west.westclient.api.login.event.PhoneExietEvent;
import com.easy.west.westclient.api.login.event.RegistSuccessEvent;
import com.google.gson.Gson;
import com.grandbroad.eim.R;
import com.grandbroad.eim.app.MyApplication;
import com.grandbroad.eim.base.BaseActivity;
import com.grandbroad.eim.event.PhoneDispatchEvent;
import com.grandbroad.eim.utils.CacheUtils;
import com.grandbroad.eim.utils.Macher;
import com.grandbroad.eim.utils.SmsTimeUtils;
import com.grandbroad.eim.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.common.Callback;
import org.xutils.common.util.MD5;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.iwgang.countdownview.CountdownView;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

public class RegisterActivity extends BaseActivity {

    @BindView(R.id.img_back_btn)
    ImageView imgBackBtn;
    @BindView(R.id.tool_bar)
    Toolbar toolBar;
    @BindView(R.id.edit_phone_input)
    EditText editPhoneInput;
    @BindView(R.id.tv_phone_state)
    TextView tvPhoneState;
    @BindView(R.id.edit_password_input)
    EditText editPasswordInput;
    @BindView(R.id.tv_password_state)
    TextView tvPasswordState;
    @BindView(R.id.edit_password_input_again)
    EditText editPasswordInputAgain;
    @BindView(R.id.tv_password_state_again)
    TextView tvPasswordStateAgain;
    @BindView(R.id.edit_code_input)
    EditText editCodeInput;
    @BindView(R.id.tv_code_state)
    TextView tvCodeState;
    @BindView(R.id.btn_register)
    Button btnRegister;
    @BindView(R.id.count_down_view)
    TextView countDownView;
    @BindView(R.id.pro_verfile_bar)
    ProgressBar proVerfileBar;
    @BindView(R.id.tv_goto_login)
    TextView tvGotoLogin;
    @BindView(R.id.tv_login_state)
    TextView tvLoginState;
    //验证码handler
    private EventHandler eh;
    //验证码发送中
    private int CODE_SENDING = 11;
    //验证码发送成功
    private int CODE_SENDSUCCESS = 12;
    //验证码发送失败
    private int CODE_SENDFAILD = 13;
    private int CODE_STATE;
    private String phone_state = "手机号码格式不正确";
    private boolean issee = false;
    private String password;
    private boolean canRegist = false;
    private String phone;
    //微信绑定api
    private String WHCHAT_REFISTER = Constants.BASE_URL + "wechatauth/appRegister";
    private String WHCHAT_NAME=null;
    private String WHCHAT_AVATAR=null;
    private boolean WHCHAT_MODE=false;
    private String UN_BIND_ID=null;
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 10) {
                tvCodeState.setVisibility(View.GONE);
                showProgessDialog("注册中");
                //进入执行账号与微信绑定
                if (WHCHAT_MODE)
                {
                    bindthisAccount();

                }
                else
                {
                    //请求注册接口
                    MyApplication.getMoleclient().regist(phone, password);
                }

            }
            if (msg.what == 11) {
                tvCodeState.setVisibility(View.VISIBLE);
            }
            return true;
        }
    });

    @Override
    protected void initview() {
        //初始化
        initSMS();
        //初始化事件
        initsession();

    }

    private void initsession() {
        tvGotoLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("phone", phone);
                EventBus.getDefault().post(new PhoneDispatchEvent(phone));
                startActivityWithBundle(LoginActivity.class, true, bundle);
            }
        });
        //手机号码验证
        //手机号输入
        editPhoneInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                String s = editPhoneInput.getText().toString();
                if (!hasFocus) {

                    if (s.length() >= 11) {
                        //验证
                        //因为是边输入边验证 从11位开始
                        boolean isphone = Macher.isPhone(s);
                        if (!isphone) {
                            tvGotoLogin.setVisibility(View.GONE);
                            /*
                            tvPhoneState.setText(phone_state);
                            tvPhoneState.setVisibility(View.VISIBLE);
                            */
                        } else {
                            phone = s;
                            tvPhoneState.setVisibility(View.GONE);
                            //验证手机号码是否存在
                            proVerfileBar.setVisibility(View.VISIBLE);
                            MyApplication.getMoleclient().isPhoneExit(s);
                        }
                    } else {
                        tvPhoneState.setText(phone_state);
                        tvPhoneState.setVisibility(View.GONE);
                        tvGotoLogin.setVisibility(View.GONE);
                    }

                } else {
                    tvPhoneState.setVisibility(View.GONE);
                }

            }
        });
        editPasswordInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    Pattern p = Pattern.compile("[a-zA-z]");
                    Pattern p1 = Pattern.compile("[0-9]");
                    //焦点变化时验证
                    password = editPasswordInput.getText().toString();
                    if (password.length() < 6) {
                        tvPasswordState.setVisibility(View.VISIBLE);
                        Log.e("不足6位", "emm");
                        Snackbar.make(editPasswordInput, "密码为6位及以上对数字字母组合", Snackbar.LENGTH_SHORT).show();
                        return;
                    }
                    if (!p.matcher(password).find()) {
                        tvPasswordState.setVisibility(View.VISIBLE);
                        //未找到字母
                        Snackbar.make(editPasswordInput, "密码为6位及以上对数字字母组合", Snackbar.LENGTH_SHORT).show();
                        return;
                    }
                    if (!p1.matcher(password).find()) {
                        tvPasswordState.setVisibility(View.VISIBLE);
                        //未找到数字
                        Snackbar.make(editPasswordInput, "密码为6位及以上对数字字母组合", Snackbar.LENGTH_SHORT).show();
                    }
                } else {
                    //获取焦点时隐藏
                    tvPasswordState.setVisibility(View.GONE);
                }

            }
        });
        editPasswordInputAgain.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    if (!TextUtils.isEmpty(password)) {
                        if (!password.equals(editPasswordInputAgain.getText().toString())) {
                            canRegist = false;
                            tvPasswordStateAgain.setVisibility(View.VISIBLE);
                            Snackbar.make(editPasswordInputAgain, "两次密码需一致", Snackbar.LENGTH_SHORT).show();
                        } else {
                            canRegist = true;
                        }
                    }
                } else {
                    tvPasswordStateAgain.setVisibility(View.GONE);
                }
            }
        });
        //设置右边edittext点击事件图标
        editPasswordInput.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                //获取drawable,右边的
                //Drawable drawable_emmm = editPasswordInput.getCompoundDrawables()[2];
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        //只看按下
                        if (event.getX() > editPasswordInput.getWidth() - editPasswordInput.getCompoundDrawables()[2].getBounds().width()) {
                            setEditPasswordState(false);
                            if (!issee) {
                                Log.d("lyb", "444");
                                //点击之后执行的事件
                                //执行对应逻辑,读取图片资源
                                Drawable drawable_see = getResources().getDrawable(R.drawable.icon_password_visual);
                                drawable_see.setBounds(0, 0, drawable_see.getIntrinsicWidth(), drawable_see.getIntrinsicHeight());
                                //替换
                                editPasswordInput.setCompoundDrawables(null, null, drawable_see, null);
                                //设置edit样式
                                editPasswordInput.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                                editPasswordInput.setSelection(editPasswordInput.getText().toString() == null ? 0 : editPasswordInput.getText().toString().length());
                                //重绘
                                editPasswordInput.postInvalidate();
                                setEditPasswordState(true);
                                issee = true;
                                return true;
                            } else {
                                if (event.getX() > editPasswordInput.getWidth() - editPasswordInput.getCompoundDrawables()[2].getBounds().width()) {
                                    Log.d("lyb", "444");
                                    //点击之后执行的事件
                                    //执行对应逻辑,读取图片资源
                                    Drawable drawable_see = getResources().getDrawable(R.drawable.icon_login_password_hide);
                                    drawable_see.setBounds(0, 0, drawable_see.getIntrinsicWidth(), drawable_see.getIntrinsicHeight());
                                    //替换
                                    editPasswordInput.setCompoundDrawables(null, null, drawable_see, null);
                                    editPasswordInput.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                                    editPasswordInput.setSelection(editPasswordInput.getText().toString() == null ? 0 : editPasswordInput.getText().toString().length());
                                    //重绘
                                    editPasswordInput.postInvalidate();
                                    setEditPasswordState(true);
                                    issee = false;
                                    return true;
                                }
                            }
                        }

                        break;
                }


                return false;
            }
        });
        //短信验证码获取
        countDownView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phone = editPhoneInput.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    return;
                }
                if (Macher.isPhone(phone)) {
                    //请求验证码
                    SMSSDK.getVerificationCode("86", phone);
                } else {
                    tvPhoneState.setText(phone_state);
                    tvPhoneState.setVisibility(View.VISIBLE);
                }

            }
        });
        //倒计时监听器
        /*
        countDownView.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
            @Override
            public void onEnd(CountdownView cv) {
                //结束
                countDownView.setVisibility(View.GONE);
                tvCodeGet.setVisibility(View.VISIBLE);
            }
        });
        */
        //点击注册
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String code = editCodeInput.getText().toString();
                if (TextUtils.isEmpty(editPasswordInput.getText().toString()) || TextUtils.isEmpty(password)) {
                    Snackbar.make(editCodeInput, "请设置密码", Snackbar.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(phone)) {
                    Snackbar.make(editCodeInput, "请输入手机号", Snackbar.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(code)) {
                    Snackbar.make(editCodeInput, "请输入验证码", Snackbar.LENGTH_SHORT).show();
                    return;
                }
                if (Macher.isPhone(phone)) {
                    //测试提交验证码
                    SMSSDK.submitVerificationCode("86", phone, code);
                } else {
                    Snackbar.make(editCodeInput, "手机号码不合法", Snackbar.LENGTH_SHORT).show();
                }

            }
        });
        imgBackBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    public void setEditPasswordState(boolean state) {
        editPasswordInput.setFocusable(state);
        editPasswordInput.setFocusableInTouchMode(state);
    }


    private void initSMS() {
        eh = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {

                if (result == SMSSDK.RESULT_COMPLETE) {
                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提交验证码成功,验证是否正确
                        Log.e("信息", "提交验证码成功:" + result);
                        CODE_STATE = CODE_SENDING;
                        if (result == SMSSDK.RESULT_COMPLETE) {
                            // TODO 处理验证码验证通过的结果
                            Message m = new Message();
                            m.what = 10;
                            handler.sendMessage(m);
                            handler.obtainMessage();
                        } else {
                            // TODO 处理错误的结果
                            Message m1 = new Message();
                            m1.what = 11;
                            handler.sendMessage(m1);
                            handler.obtainMessage();
                            ((Throwable) data).printStackTrace();

                        }
                        //进入倒计时
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        //获取验证码成功
                        Log.e("信息", "获取验证码成功:" + result);
                        CODE_STATE = CODE_SENDSUCCESS;
                        //开始倒计时
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                countDownView.setVisibility(View.VISIBLE);
                                SmsTimeUtils.check(SmsTimeUtils.SETTING_FINANCE_ACCOUNT_TIME, false);
                                SmsTimeUtils.startCountdown(countDownView);
                            }
                        });


                    } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                        //返回支持发送验证码的国家列表

                    }
                } else {
                    ((Throwable) data).printStackTrace();
                }
            }
        };
        SMSSDK.registerEventHandler(eh); //注册短信回调
    }

    @Override
    protected void initdata() {
        //判断计时器状态,检查是否是第一次计时
        if (SmsTimeUtils.check(SmsTimeUtils.SETTING_FINANCE_ACCOUNT_TIME, true)) {
            SmsTimeUtils.startCountdown(countDownView);
        }
        //获取
        if (getIntent().getExtras()!=null)
        {
            Bundle bundle = getIntent().getExtras();
            WHCHAT_MODE = bundle.getBoolean("mode");
            UN_BIND_ID = bundle.getString("unbindid");
            WHCHAT_NAME =bundle.getString("name");
            WHCHAT_AVATAR = bundle.getString("avatar");
            if (WHCHAT_MODE)
            {
                tvLoginState.setText("注册鼹鼠智享");
                btnRegister.setText("注册并绑定");
            }
        }

    }

    @Override
    protected int setlayout() {
        return R.layout.activity_register;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterAllEventHandler();
    }

    /**
     * 注册
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void register(RegistSuccessEvent event) {
        if (event.isOk()) {
            ReturenUser user = event.getBean();
            if (user.getStatus() == 1) {

                CacheUtils.saveUser(user.getData());

                dissmissDialog();
                //成功
                startActivity(HomeActivity.class, true);
                finish();
            } else {
                //
                Snackbar.make(editCodeInput, "注册失败", Snackbar.LENGTH_SHORT).show();
            }
            dissmissDialog();
        } else {
            dissmissDialog();
        }
    }

    private void bindthisAccount() {
        RequestParams params = new RequestParams(WHCHAT_REFISTER);
        //md5加密
        String format = MD5.md5(password);
        params.addBodyParameter("phone",phone);
        params.addBodyParameter("pwd",format);
        params.addBodyParameter("avatar",WHCHAT_AVATAR);
        params.addBodyParameter("name",WHCHAT_NAME);
        params.addBodyParameter("unionId",UN_BIND_ID);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    ReturenUser returenUser = new Gson().fromJson(result,ReturenUser.class);
                    if (returenUser!=null)
                    {
                        CacheUtils.saveUser(returenUser.getData());
                        ToastUtils.show("绑定成功");
                        startActivity(HomeActivity.class,true);

                    }
                    else
                    {
                        ToastUtils.show("注册失败");
                    }
                }
                catch (Exception c)
                {
                    ToastUtils.show("微信登陆失败");
                }
                finally {
                    dissmissDialog();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtils.show(ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                ToastUtils.show(cex.getMessage());
            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 判断手机号是否存在
     *
     * @param eva
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void isphoneexit(PhoneExietEvent eva) {
        if (eva.isOk()) {
            boolean is = eva.getBean();
            if (is) {

                btnRegister.setBackgroundResource(R.drawable.btn_shape);
                btnRegister.setClickable(true);
                tvPhoneState.setVisibility(View.GONE);
                proVerfileBar.setVisibility(View.GONE);
                tvGotoLogin.setVisibility(View.GONE);
            } else {
                String show = "该手机已注册!";
                proVerfileBar.setVisibility(View.GONE);
                btnRegister.setBackgroundResource(R.drawable.not_btn_bg);
                btnRegister.setClickable(false);
                tvPhoneState.setText(show);
                tvPhoneState.setVisibility(View.VISIBLE);
                tvGotoLogin.setVisibility(View.VISIBLE);
            }

        }
    }


}
